/********************************************************************
 * Copyright(c) 2023-2023 Grayson Zheng.
 * File: uart.C
 * Description: Driver for HC-SR04 ultrasonic ranging module.
 * Version: 1.0
 * Date: 2023-07-21
 * Author: zhengxinyu13@qq.com
 * ---------- Revision History ----------
 * <version>
 * <date>
 * <author>
 * <desc>
 * Modified to be suitable to the new coding rules in all functions.
 ********************************************************************/

#include "hc-sr04.h"
#include <stdio.h>
#include <string.h>

void time0_init(void)
{
	TMOD &= 0xF0;
	TMOD |= 0x01;
}

void start_ultrasonic(void)
{
	SET_BIT(TRIG);
	delay_10us();
	RESET_BIT(TRIG);
}

fp_64 get_distance(void)
{
	RESET(TH0);
	RESET(TL0);
	start_ultrasonic();
	while (!ECHO);
	TR0 = TURN_ON;
	while (ECHO);
	TR0 = TURN_OFF;

	return (fp_64)((SHIFT_8_BITS_LEFT(TH0) + TL0) * (MACHINE_CYCLE * (SPEED_SOUND * HALF)));
}

void distance_string(uint_8 *string, uint_16 len)
{
	uint_8 i = 0;
	
	fp_64 distance = get_distance();

	memset(string, '\0', len);
	sprintf(string, "%.2fcm\r\n", distance);
}